8545. Multiplication table

 

Print an n × n multiplication table with alignment.

 

Input. One integer n (1 ≤ n ≤ 9).

 

Output. Print an n × n multiplication table, formatted as shown in the example.

 

Sample input

Sample output

5

1  2  3  4  5

2  4  6  8 10

3  6  9 12 15

4  8 12 16 20

5 10 15 20 25

 

 

SOLUTION

loops

 

Algorithm analysis

Use a nested loop to print the multiplication table.

 

Algorithm implementation

Read the input value n.

 

scanf("%d",&n);

 

Using a double loop, print the multiplication table. To ensure alignment, each number should occupy two positions. Use the %2d format for output.

 

for (i = 1; i <= n; i++)

{

  for (j = 1; j <= n; j++)

    printf("%2d ", i * j);

  printf("\n");

}

 

Java implementation

 

import java.util.*;

 

public class Main

{

  public static void main(String[] args)

  {

    Scanner con = new Scanner(System.in);

    int n = con.nextInt();

    int m[][] = new int[n+1][n+1];

 

    for(int i = 1; i <= n; i++)

    for(int j = 1; j <= n; j++)

      m[i][j] = i * j;

 

    for(int i = 1; i <= n; i++)

    {

      for(int j = 1; j <= n; j++)

        System.out.printf("%2d ", m[i][j]);

      System.out.println();

    }

    con.close();

  }

}

 

Python implementation

Read the input value n.

 

n = int(input())

 

Using a double loop, print the multiplication table. To ensure alignment, each number should occupy two positions. Use the %2d format for output.

 

for x in range(1, n + 1):

  for y in range(1, n + 1):

    print("%2d" %(x * y), end=' ')

  print()